package com.qf.realm;

import com.qf.pojo.SysUsers;
import com.qf.service.MenuService;
import com.qf.service.RoleService;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    MenuService menuService;

    //提供授权信息(权限信息): 根据用户获取权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //要强制转换为哪个对象，关键是 在 认证时存储到session中的对象类型
        SysUsers user = (SysUsers) principals.getPrimaryPrincipal();

        //查询角色
        Set<String> roles =roleService.findRoles(user.getId());
        //查询权限
        Set<String> perms =menuService.findPerms(user.getId());


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //需要角色信息
        authorizationInfo.setRoles(roles);
        //需要权限信息
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

    //提供认证信息(账号和密码)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //在token对象中 username是 字符串类型，直接强转
        String username = (String) token.getPrincipal();
        //在token中，password是char[] ,必须必须转换为 char[] ,在转换为 String类型
        String password = new String((char[])token.getCredentials());

        //根据用户名 ， 查询数据库，获取用户信息
        SysUsers user = userService.findByUsername(username);
        //与用户输入的 账号和密码 进行比较，如果没有问题，则登录成功
        if(user == null) {
            throw new UnknownAccountException("未知用户名");
        }
        //账户是否被锁定
        if(user.getStatus() == 0) {
            throw new LockedAccountException("账户已锁定");
        }
        //如果密码不相等，密码错误
        if(!password.equals(user.getPassword())){
            throw new CredentialsException("密码错误");
        }
        //参数1： 存储在session中的对象， 密码对象， 真实姓名
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password, user.getRealname());

        return authenticationInfo;
    }
}
